package web.servlet;

import domain.*;
import service.CartService;
import service.LogService;
import service.OrderService;
import service.ProductService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "ProductServlet", urlPatterns = {"/Product"})
public class ProductServlet extends HttpServlet {
    private OrderService orderService = new OrderService();
    private Product product;
    private Cart cart;
    private int num, toCart;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Account loginUser = (Account) session.getAttribute("loginUser");
        if(loginUser == null){
            req.getRequestDispatcher("ProductForm").forward(req,resp);
            return;
        }
        product = (Product) session.getAttribute("showingProduct");
        this.num = Integer.parseInt(req.getParameter("num"));
        Order order = orderService.productToOrder(product);
        order.setPrice(order.getUnitprice().multiply(BigDecimal.valueOf(this.num)));
        order.setUserid(loginUser.getUserid());
        order.setNum(this.num);
        List<Order> orderList = new ArrayList<>();
        orderList.add(order);
        session.setAttribute("confirmOrderList", orderList);

        //记录日志
        new LogService().newLog(new Log(loginUser.getUserid(), "直接购买了-" + this.num + "-只-" + product.getBreed() + "-宠物"));

        req.getRequestDispatcher("ConfirmOrderForm").forward(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
